from flask import Blueprint, render_template, request, jsonify, url_for, current_app
from werkzeug.utils import secure_filename
from app.common.mdnice import convert_markdown, css2style
import os

mdnice = Blueprint('mdnice', __name__)

ALLOWED_EXTENSIONS = {'md', 'markdown'}
STYLE_LIST = ['default', 'github-markdown','wechat', 'cdk8s', 'custom']

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@mdnice.route('/mdnice')
def index():
    return render_template('mediaview/mdnice.html', styles=STYLE_LIST)

@mdnice.route('/mdnice/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '没有文件'}), 400
    file = request.files['file']
    if file and allowed_file(file.filename):
        content = file.read().decode('utf-8')
        html_content = convert_markdown(content)
        return jsonify({'html': html_content, 'markdown': content})
    return jsonify({'error': '不支持的文件类型'}), 400

@mdnice.route('/mdnice/convert', methods=['POST'])
def convert():
    markdown_text = request.json.get('markdown', '')
    html_content = convert_markdown(markdown_text)
    return jsonify({'html': html_content})

@mdnice.route('/mdnice/downhtml', methods=['POST'])
def download_html():
    try:
        data = request.json
        html_content = data.get('htmlcontent')
        style_name = data.get('style', 'default')

        fn_css = style_name.split('/')[-1]
        
        # 构建CSS文件路径
        css_file = url_for('static', filename=f'css/mdnice/{fn_css}')
        # 获取物理路径
        css_file = current_app.root_path + css_file
        print("css_file == ", css_file)
        
        # 生成内联样式的HTML文件
        output_path = css2style(css_file, html_content)
        
        return jsonify({
            'code': 200,
            'msg': 'success',
            'path': '/static/outs/tempmd.html'
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'msg': str(e)
        })
